const express = require('express')
const router = express.Router()
const db = require('../db')

// 获取所有文章
router.get('/', async (req, res) => {
  try {
    const [articles] = await db.query(`
      SELECT a.*, 
        u.username as author_name, 
        u.avatar as author_avatar,
        COUNT(DISTINCT l.user_id) as like_count,
        COUNT(DISTINCT c.id) as comment_count,
        (SELECT COALESCE(SUM(share_count), 0) FROM shares WHERE article_id = a.id) as share_count,
        SUM(v.view_count) as view_count
      FROM articles a
      LEFT JOIN users u ON a.user_id = u.id
      LEFT JOIN likes l ON a.id = l.article_id
      LEFT JOIN comments c ON a.id = c.article_id
      LEFT JOIN views v ON a.id = v.article_id
      GROUP BY a.id
      ORDER BY a.create_time DESC
    `)
    res.json(articles)
  } catch (error) {
    res.status(500).json({ error: '获取文章失败' })
  }
})

// 获取单篇文章及其评论

// 添加新文章
router.post('/', async (req, res) => {
  try {
    const { user_id, category, title, summary, content } = req.body
    console.log('接收到的数据:', req.body)

    // 详细的字段验证
    if (!user_id) {
      return res.status(400).json({ error: '缺少用户ID' })
    }
    if (!title) {
      return res.status(400).json({ error: '缺少文章标题' })
    }
    if (!content) {
      return res.status(400).json({ error: '缺少文章内容' })
    }

    // 验证用户是否存在
    const [users] = await db.query('SELECT id FROM users WHERE id = ?', [user_id])
    if (users.length === 0) {
      return res.status(400).json({ error: '用户不存在' })
    }

    const [result] = await db.query(
      `INSERT INTO articles 
       (user_id, category, title, summary, content) 
       VALUES (?, ?, ?, ?, ?)`,
      [
        parseInt(user_id),
        category || null,
        title,
        summary || null,
        content || null
      ]
    )

    console.log('SQL执行结果:', result)

    if (result.affectedRows === 1) {
      res.json({ id: result.insertId })
    } else {
      throw new Error('插入失败')
    }
  } catch (error) {
    console.error('创建文章失败:', error.message)
    res.status(500).json({ 
      error: '创建文章失败',
      details: error.message 
    })
  }
})

// 更新文章
router.put('/:id', async (req, res) => {
  try {
    const { category, title, summary, content } = req.body
    await db.query(
      'UPDATE articles SET category = ?, title = ?, summary = ?, content = ? WHERE id = ?',
      [category, title, summary, content, req.params.id]
    )
    res.json({ message: '更新成功' })
  } catch (error) {
    res.status(500).json({ error: '更新文章失败' })
  }
})

// 删除文章
router.delete('/:id', async (req, res) => {
  try {
    await db.query('DELETE FROM articles WHERE id = ?', [req.params.id])
    res.json({ message: '删除成功' })
  } catch (error) {
    res.status(500).json({ error: '删除文章失败' })
  }
})

// 获取文章评论
router.get('/:id/comments', async (req, res) => {
  try {
    const [comments] = await db.query(
      `SELECT c.*, u.username as author_name, u.avatar as author_avatar 
       FROM comments c
       JOIN users u ON c.user_id = u.id
       WHERE c.article_id = ?
       ORDER BY c.create_time DESC`,
      [req.params.id]
    )
    // console.log(comments);
    
    res.json(comments)
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 添加评论
router.post('/:id/comments', async (req, res) => {
  try {
    const result = await db.query(
      'INSERT INTO comments (article_id, user_id, content) VALUES (?, ?, ?)',
      [req.params.id, req.body.user_id, req.body.content]
    )
    res.json({ id: result.insertId })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 点赞评论
router.post('/comments/:id/like', async (req, res) => {
  try {
    await db.query(
      'UPDATE comments SET like_count = like_count + 1 WHERE id = ?',
      [req.params.id]
    )
    res.json({ message: 'Success' })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 取消点赞评论
router.delete('/comments/:id/like', async (req, res) => {
  try {
    await db.query(
      'UPDATE comments SET like_count = GREATEST(like_count - 1, 0) WHERE id = ?',
      [req.params.id]
    )
    res.json({ message: 'Success' })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 检查用户是否点赞过文章
router.get('/:articleId/:userId/like/check', async (req, res) => {
  try {
    const { articleId, userId } = req.params
    if (!articleId || !userId || articleId === 'undefined' || userId === 'undefined') {
      return res.status(400).json({ error: '缺少必要参数' })
    }

    const [result] = await db.query(
      'SELECT EXISTS(SELECT 1 FROM likes WHERE article_id = ? AND user_id = ?) as is_liked',
      [articleId, userId]
    )
    res.json(!!result[0].is_liked)
  } catch (error) {
    res.status(500).json({ error: '检查点赞状态失败' })
  }
})

// 点赞文章
router.post('/:articleId/:userId/like', async (req, res) => {
  try {
    const { articleId, userId } = req.params
    if (!articleId || !userId || articleId === 'undefined' || userId === 'undefined') {
      return res.status(400).json({ error: '缺少必要参数' })
    }

    const [existing] = await db.query(
      'SELECT * FROM likes WHERE article_id = ? AND user_id = ?',
      [articleId, userId]
    )

    if (existing.length > 0) {
      return res.status(400).json({ error: '已经点赞过了' })
    }

    await db.query(
      'INSERT INTO likes (article_id, user_id) VALUES (?, ?)',
      [articleId, userId]
    )

    res.json({ message: '点赞成功' })
  } catch (error) {
    res.status(500).json({ error: '点赞失败' })
  }
})

// 取消点赞
router.delete('/:articleId/:userId/like', async (req, res) => {
  try {
    const { articleId, userId } = req.params
    if (!articleId || !userId || articleId === 'undefined' || userId === 'undefined') {
      return res.status(400).json({ error: '缺少必要参数' })
    }

    await db.query(
      'DELETE FROM likes WHERE article_id = ? AND user_id = ?',
      [articleId, userId]
    )
    res.json({ message: '取消点赞成功' })
  } catch (error) {
    res.status(500).json({ error: '取消点赞失败' })
  }
})

// 转发文章
router.post('/:articleId/:userId/share', async (req, res) => {
  try {
    const { articleId, userId } = req.params
    if (!articleId || !userId || articleId === 'undefined' || userId === 'undefined') {
      return res.status(400).json({ error: '缺少必要参数' })
    }

    const [existing] = await db.query(
      'SELECT * FROM shares WHERE article_id = ? AND user_id = ?',
      [articleId, userId]
    )

    if (existing.length > 0) {
      // 如果已经有记录，增加转发次数
      await db.query(
        'UPDATE shares SET share_count = share_count + 1 WHERE article_id = ? AND user_id = ?',
        [articleId, userId]
      )
    } else {
      // 如果是第一次转发，创建新记录
      await db.query(
        'INSERT INTO shares (article_id, user_id, share_count) VALUES (?, ?, 1)',
        [articleId, userId]
      )
    }

    res.json({ message: '转发成功' })
  } catch (error) {
    res.status(500).json({ error: '转发失败' })
  }
})

// 记录文章浏览
router.post('/:articleId/:userId/view', async (req, res) => {
  try {
    const { articleId, userId } = req.params
    if (!articleId || !userId || articleId === 'undefined' || userId === 'undefined') {
      return res.status(400).json({ error: '缺少必要参数' })
    }

    await db.query(`
      INSERT INTO views (article_id, user_id, view_count) 
      VALUES (?, ?, 1)
      ON DUPLICATE KEY UPDATE 
      view_count = view_count + 1,
      view_time = CURRENT_TIMESTAMP
    `, [articleId, userId])

    res.json({ message: '浏览记录已更新' })
  } catch (error) {
    res.status(500).json({ error: '记录浏览失败' })
  }
})

module.exports = router 